const { promisePool, Pool } = require('../models/db')

const systemSettingModel = require('../models/systemSettingModel')

const JWT = require('../utils/JWT')

// 导入 bcryptjs 加密包
const bcrypt = require('bcryptjs')

//导入 moment
const moment = require('moment');

const userService = {
  // 用户名是否被占用（同步方式演示）
  checkUser: (username, res) => {
    Pool.query(userModel.checkByUsername, [username], function (err, rows) {
      if (err) {
        // return res.send({ code: 1, msg: err.msg })
        return res.codeMsg(err)
      }

      if (rows.length > 0) {
        // return resp.send({ code: 1, msg: '用户名被占用，请更换其他用户名！' })
        return res.codeMsg('用户名被占用，请更换其他用户名！')
      }
    })
  },

  
  // 插入设置
  add: (req, res) => {
    const params = {
      ...req.body,
            //修改 time 属性的值
      created_at: moment().format('YYYY-MM-DD HH:mm:ss'),
      updated_at: moment().format('YYYY-MM-DD HH:mm:ss'),
    }
    Pool.query(
      systemSettingModel.addUser,
      // [{ username: username, password: password }],
      [params],
      function (err, rows) {
        console.log(err, 'err');
        console.log(params, 'params');
        if (err) {
          return res.codeMsg(err)
        }

        if (rows.affectedRows !== 1) {
          return res.codeMsg('注册用户失败，请稍后再试！')
        }

        // 注册成功提示
        // res.send({ code: 0, msg: '注册成功！' })
        return res.codeMsg('注册成功！', 0)
      }
    )
  },
  // 更新设置
  update: (req, res) => {
    const params = { ...req.body, updated_at: moment().format('YYYY-MM-DD HH:mm:ss')}
    Pool.query(
      systemSettingModel.update,
      [params, req.body.id],
      function (err, rows) {
        console.log(err, 'err');
        if (err) return res.codeMsg(err)

        if (rows.affectedRows !== 1) return res.codeMsg('更新失败！')
        console.log(111);
        return res.codeMsg('更新成功！', 0)
      }
    )
  },

    // 删除设置
  delete: (req, res) => {
    Pool.query(systemSettingModel.delete, [req.body.id], function (err, rows) {
      console.log(err, 'err');
      if (err) return res.codeMsg(err)
      console.log(1);
      if (rows.affectedRows !== 1) return res.codeMsg('您要删除的内存不存在！')
      console.log(2);
      return res.codeMsg('删除成功！', 0)
    })
  },

  // 用户登录
  loginUser: (username, password, res) => {
    Pool.query(userModel.checkByUsername, [username], function (err, rows) {
      if (err) {
        return res.codeMsg(err)
      }

      // 用户是否存在
      if (rows.length !== 1) {
        return res.codeMsg('用户名不存在！')
      }

      // 密码是否正确（使用✨bcrypt.compareSync()对密码进行比较）
      const compareResult = bcrypt.compareSync(password, rows[0].password)

      if (!compareResult) {
        return res.codeMsg('密码错误！')
      }

      // 🚩设置token签名
      // 1、生成token
      const user = { ...rows[0], password: '', user_pic: '' } // 利用展开运算符的方式排出密码、照片等敏感信息
      const tokenStr = JWT.generate(user)

      // 2、发送token到客户端（header方式）
      // res.header('Authorization', token)
      return res.send({
        code: 0,
        msg: '登录成功',
        data: {
          token: 'Bearer ' + tokenStr,
          account: username
        }
      })

      // 登录成功
      // res.codeMsg('登录成功', 0)
    })
  },

  // 获取用户id
  getMenuId: (username, password, res) => {
    return res.send({
      code: 0,
      msg: '成功',
      data: [
              {
                  "id": 1,
                  "pid": 0,
                  "status": 1,
                  "type": 0,
                  "code": "A01",
                  "name": "基础管理",
                  "identification": null,
                  "url": "sys",
                  "icon": "base",
                  "memo": "sys",
                  "sort": 2,
                  "creator_id": 1,
                  "updater_id": 1,
                  "created_at": "2023-11-24 15:44:08",
                  "updated_at": "2023-11-24 15:44:08",
                  "children": [
                      {
                          "id": 3,
                          "pid": 1,
                          "status": 1,
                          "type": 1,
                          "code": "A0102",
                          "name": "用户管理",
                          "identification": null,
                          "url": "/sys/user",
                          "icon": "roleManage",
                          "memo": null,
                          "sort": 2,
                          "creator_id": 1,
                          "updater_id": 1,
                          "created_at": "2023-11-24 15:44:08",
                          "updated_at": "2023-11-24 15:44:08",
                          "children": []
                      },
                      {
                          "id": 2,
                          "pid": 1,
                          "status": 1,
                          "type": 1,
                          "code": "A0101",
                          "name": "菜单管理",
                          "identification": null,
                          "url": "/sys/menu",
                          "icon": "menu",
                          "memo": null,
                          "sort": 1,
                          "creator_id": 1,
                          "updater_id": 1,
                          "created_at": "2023-11-24 16:06:05",
                          "updated_at": "2023-11-24 16:06:10",
                          "children": []
                      },
                      {
                          "id": 31,
                          "pid": 1,
                          "status": 1,
                          "type": 1,
                          "code": null,
                          "name": "配置项管理",
                          "identification": null,
                          "url": "sys/system-item-setting",
                          "icon": "base",
                          "memo": null,
                          "sort": null,
                          "creator_id": 1,
                          "updater_id": 1,
                          "created_at": "2024-04-08 13:42:03",
                          "updated_at": "2024-04-08 13:42:21",
                          "children": []
                      }
                  ]
              },
              {
                  "id": 12,
                  "pid": 0,
                  "status": 1,
                  "type": 0,
                  "code": null,
                  "name": "种植区域管理",
                  "identification": null,
                  "url": "tree",
                  "icon": "tree",
                  "memo": "种植管理",
                  "sort": 1,
                  "creator_id": 1,
                  "updater_id": 1,
                  "created_at": "2024-03-12 09:47:27",
                  "updated_at": "2024-03-12 15:43:17",
                  "children": [
                      {
                          "id": 10,
                          "pid": 12,
                          "status": 1,
                          "type": 1,
                          "code": null,
                          "name": "种植区域",
                          "identification": null,
                          "url": "/tree/area",
                          "icon": "area",
                          "memo": "种植区域",
                          "sort": 4,
                          "creator_id": 1,
                          "updater_id": 1,
                          "created_at": "2024-03-12 09:43:40",
                          "updated_at": "2024-03-13 09:27:23",
                          "children": []
                      },
                      {
                          "id": 15,
                          "pid": 12,
                          "status": 1,
                          "type": 1,
                          "code": null,
                          "name": "种植树种",
                          "identification": null,
                          "url": "/tree/treeList",
                          "icon": "tree",
                          "memo": "种植树种",
                          "sort": 2,
                          "creator_id": 1,
                          "updater_id": 1,
                          "created_at": "2024-03-12 09:51:02",
                          "updated_at": "2024-03-12 15:43:36",
                          "children": []
                      },
                      {
                          "id": 21,
                          "pid": 12,
                          "status": 1,
                          "type": 1,
                          "code": null,
                          "name": "种植规格",
                          "identification": null,
                          "url": "/tree/specList",
                          "icon": "spec",
                          "memo": "种植规格",
                          "sort": 1,
                          "creator_id": 1,
                          "updater_id": 1,
                          "created_at": "2024-03-12 14:26:48",
                          "updated_at": "2024-03-13 09:30:18",
                          "children": []
                      }
                  ]
              },
              {
                  "id": 22,
                  "pid": 0,
                  "status": 1,
                  "type": 0,
                  "code": null,
                  "name": "捐赠管理",
                  "identification": null,
                  "url": "donate",
                  "icon": "juan",
                  "memo": "捐赠管理",
                  "sort": 0,
                  "creator_id": 1,
                  "updater_id": 1,
                  "created_at": "2024-03-12 15:45:35",
                  "updated_at": "2024-03-13 09:26:21",
                  "children": [
                      {
                          "id": 23,
                          "pid": 22,
                          "status": 1,
                          "type": 1,
                          "code": null,
                          "name": "捐赠记录",
                          "identification": null,
                          "url": "/donate/record",
                          "icon": "juan",
                          "memo": "捐赠记录",
                          "sort": null,
                          "creator_id": 1,
                          "updater_id": 1,
                          "created_at": "2024-03-12 15:46:31",
                          "updated_at": "2024-03-13 09:26:40",
                          "children": []
                      }
                  ]
              }
            ]
      })
    return
    Pool.query(userModel.checkByUsername, [username], function (err, rows) {
      if (err) {
        return res.codeMsg(err)
      }

      // 用户是否存在
      if (rows.length !== 1) {
        return res.codeMsg('用户名不存在！')
      }

      // 密码是否正确（使用✨bcrypt.compareSync()对密码进行比较）
      const compareResult = bcrypt.compareSync(password, rows[0].password)

      if (!compareResult) {
        return res.codeMsg('密码错误！')
      }

      // 🚩设置token签名
      // 1、生成token
      const user = { ...rows[0], password: '', user_pic: '' } // 利用展开运算符的方式排出密码、照片等敏感信息
      const tokenStr = JWT.generate(user)

      // 2、发送token到客户端（header方式）
      // res.header('Authorization', token)
      return res.send({
        code: 0,
        msg: '登录成功',
        data: {
          token: 'Bearer ' + tokenStr,
          account: username
        }
      })

      // 登录成功
      // res.codeMsg('登录成功', 0)
    })
  },
  list: (res) => {
    // return res.send({
    //   code: 0,
    //   msg: '成功',
    //   data: []
    // })
    // return
    Pool.query(systemSettingModel.list, function (err, rows) {
      if (err) {
        return res.codeMsg(err)
      }

      const data = rows.map(item => {
      const created_at = moment(item.created_at, 'D/M/YYYY HH:mm:ss', true)
      const updated_at = moment(item.updated_at, 'D/M/YYYY HH:mm:ss', true)
      return {
        ...item,
        created_at: moment(created_at).format('YYYY-MM-DD HH:mm:ss'),
        updated_at: moment(updated_at).format('YYYY-MM-DD HH:mm:ss')
      }
    })
      // 2、发送token到客户端（header方式）
      // res.header('Authorization', token)
      return res.send({
        code: 0,
        msg: '成功',
        data
      })

      // 登录成功
      // res.codeMsg('登录成功', 0)
    })
  },
}

module.exports = userService
